<template>
  <div class="subscription-management" :class="{ 'dark': isDark }">
    <el-card class="subscription-card">
      <template #header>
        <div class="card-header">
          <h3>{{ t('dashboard.vipCenter.subscriptionManagement.mySubscription') }}</h3>
          <el-button 
            v-if="!isVip" 
            type="primary" 
            @click="showUpgrade"
            class="upgrade-btn"
          >
            {{ t('dashboard.vipCenter.subscriptionManagement.upgradeVip') }}
          </el-button>
        </div>
      </template>

      <!-- 当前订阅状态 -->
      <div class="current-subscription">
        <div v-if="currentSubscription" class="subscription-info">
          <div class="subscription-header">
            <div class="plan-info">
              <h4 class="plan-name">{{ currentSubscription.planName }}</h4>
              <el-tag 
                :type="getStatusTagType(currentSubscription.status)" 
                size="small"
              >
                {{ getSubscriptionStatusText(currentSubscription.status) }}
              </el-tag>
            </div>
            <div class="subscription-actions">
              <el-dropdown v-if="currentSubscription.status === 'ACTIVE'">
                <el-button size="small" type="text">
                  {{ t('dashboard.vipCenter.subscriptionManagement.manageSubscription') }}<el-icon class="el-icon-arrow-down"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="showCancelDialog">
                      {{ t('dashboard.vipCenter.subscriptionManagement.cancelSubscription') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <div class="subscription-details">
            <div class="detail-row">
              <span class="label">{{ t('dashboard.vipCenter.subscriptionManagement.startTime') }}</span>
              <span class="value">{{ formatDate(currentSubscription.startDate) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">{{ t('dashboard.vipCenter.subscriptionManagement.endTime') }}</span>
              <span class="value">{{ formatDate(currentSubscription.endDate) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">{{ t('dashboard.vipCenter.subscriptionManagement.daysLeft') }}</span>
              <span class="value" :class="getDaysLeftClass(currentSubscription.daysLeft)">
                {{ currentSubscription.daysLeft }}{{ t('dashboard.vipCenter.subscriptionManagement.daysUnit') }}
              </span>
            </div>
            <div class="detail-row">
              <span class="label">{{ t('dashboard.vipCenter.subscriptionManagement.actualAmount') }}</span>
              <span class="value amount">{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ currentSubscription.actualAmount?.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <div v-else class="no-subscription">
          <el-empty 
            :description="t('dashboard.vipCenter.subscriptionManagement.noSubscription')"
            :image-size="120"
          >
            <el-button type="primary" @click="showUpgrade">
              {{ t('dashboard.vipCenter.subscriptionManagement.activateVipNow') }}
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 订阅历史 -->
      <div v-if="subscriptions.length > 1" class="subscription-history">
        <h4 class="history-title">{{ t('dashboard.vipCenter.subscriptionManagement.subscriptionHistory') }}</h4>
        <div class="history-list">
          <div
            v-for="subscription in otherSubscriptions"
            :key="subscription.id"
            class="history-item"
          >
            <div class="item-header">
              <span class="plan-name">{{ subscription.planName }}</span>
              <el-tag 
                :type="getStatusTagType(subscription.status)" 
                size="small"
              >
                {{ getSubscriptionStatusText(subscription.status) }}
              </el-tag>
            </div>
            <div class="item-details">
              <span class="detail">{{ formatDate(subscription.startDate) }} - {{ formatDate(subscription.endDate) }}</span>
              <span class="amount">{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ subscription.actualAmount?.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 支付订单历史 -->
    <el-card class="orders-card">
      <template #header>
        <h3>{{ t('dashboard.vipCenter.subscriptionManagement.paymentRecords') }}</h3>
      </template>
      
      <el-table :data="paymentOrders" style="width: 100%">
        <el-table-column prop="orderNo" :label="t('dashboard.vipCenter.subscriptionManagement.orderNo')" width="180" />
        <el-table-column prop="planType" :label="t('dashboard.vipCenter.subscriptionManagement.planType')" width="120">
          <template #default="{ row }">
            {{ getPlanTypeText(row.planType) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" :label="t('dashboard.vipCenter.subscriptionManagement.amount')" width="100">
          <template #default="{ row }">
            {{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ row.amount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="t('dashboard.vipCenter.subscriptionManagement.status')" width="100">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusTagType(row.status)" size="small">
              {{ getOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" :label="t('dashboard.vipCenter.subscriptionManagement.paymentMethod')" width="100">
          <template #default="{ row }">
            {{ getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" :label="t('dashboard.vipCenter.subscriptionManagement.createTime')" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAt" :label="t('dashboard.vipCenter.subscriptionManagement.paymentTime')" width="180">
          <template #default="{ row }">
            {{ row.paidAt ? formatDateTime(row.paidAt) : '-' }}
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="paymentOrdersPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 取消订阅确认对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      :title="t('dashboard.vipCenter.subscriptionManagement.cancelSubscriptionConfirm')"
      width="400px"
    >
      <div class="cancel-content">
        <el-alert
          :title="t('dashboard.vipCenter.subscriptionManagement.confirmCancelSubscription')"
          type="warning"
          :closable="false"
          show-icon
        >
          <p>{{ t('dashboard.vipCenter.subscriptionManagement.cancelWarning') }}</p>
        </el-alert>
      </div>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">{{ t('dashboard.vipCenter.subscriptionManagement.cancel') }}</el-button>
        <el-button type="danger" @click="confirmCancelSubscription">
          {{ t('dashboard.vipCenter.subscriptionManagement.confirmCancel') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useVipStore } from '@/stores/vip'
import { useThemeStore } from '@/stores/theme'

const { t } = useI18n()
const vipStore = useVipStore()
const themeStore = useThemeStore()

// 计算当前是否为暗色模式
const isDark = computed(() => themeStore.isDark)

// 响应式数据
const cancelDialogVisible = ref(false)

// 计算属性
const isVip = computed(() => vipStore.isVip)
const currentSubscription = computed(() => vipStore.currentSubscription)
const subscriptions = computed(() => vipStore.subscriptions)
const paymentOrders = computed(() => vipStore.paymentOrders)
const paymentOrdersPagination = computed(() => vipStore.paymentOrdersPagination)

const otherSubscriptions = computed(() => {
  return subscriptions.value.filter(sub => sub.id !== currentSubscription.value?.id)
})

onMounted(async () => {
  await vipStore.init()
})

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)

// 方法
const showUpgrade = () => {
  vipStore.showUpgradeDialog()
}

const showCancelDialog = () => {
  cancelDialogVisible.value = true
}

const confirmCancelSubscription = async () => {
  try {
    if (currentSubscription.value) {
      await vipStore.cancelSubscription(currentSubscription.value.id)
      ElMessage.success(t('dashboard.vipCenter.subscriptionManagement.subscriptionCancelled'))
      cancelDialogVisible.value = false
    }
  } catch (error: any) {
    ElMessage.error(error.message || t('dashboard.vipCenter.subscriptionManagement.cancelFailed'))
  }
}

const formatDate = (dateString: string) => {
  return vipStore.formatDate(dateString)
}

const formatDateTime = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': 'success',
    'EXPIRED': 'info',
    'CANCELLED': 'warning',
    'PENDING': 'warning'
  }
  return statusMap[status] || 'info'
}

const getOrderStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PAID': 'success',
    'PENDING': 'warning',
    'FAILED': 'danger',
    'CANCELLED': 'info'
  }
  return statusMap[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PAID': t('dashboard.vipCenter.subscriptionManagement.orderStatus.paid'),
    'PENDING': t('dashboard.vipCenter.subscriptionManagement.orderStatus.pending'),
    'FAILED': t('dashboard.vipCenter.subscriptionManagement.orderStatus.failed'),
    'CANCELLED': t('dashboard.vipCenter.subscriptionManagement.orderStatus.cancelled')
  }
  return statusMap[status] || status
}

const getSubscriptionStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': t('dashboard.vipCenter.subscriptionManagement.subscriptionStatus.active'),
    'EXPIRED': t('dashboard.vipCenter.subscriptionManagement.subscriptionStatus.expired'),
    'CANCELLED': t('dashboard.vipCenter.subscriptionManagement.subscriptionStatus.cancelled'),
    'PENDING': t('dashboard.vipCenter.subscriptionManagement.subscriptionStatus.pending')
  }
  return statusMap[status] || status
}

const getPlanTypeText = (planType: string) => {
  const planMap: Record<string, string> = {
    'MONTHLY_VIP': t('dashboard.vipCenter.subscriptionManagement.monthlyVip'),
    'YEARLY_VIP': t('dashboard.vipCenter.subscriptionManagement.yearlyVip')
  }
  return planMap[planType] || planType
}

const getPaymentMethodText = (method: string) => {
  const methodMap: Record<string, string> = {
    'ALIPAY': t('dashboard.vipCenter.subscriptionManagement.paymentMethods.alipay'),
    'WECHAT': t('dashboard.vipCenter.subscriptionManagement.paymentMethods.wechat'),
    'MANUAL': t('dashboard.vipCenter.subscriptionManagement.paymentMethods.manual')
  }
  return methodMap[method] || method
}

const getDaysLeftClass = (days?: number) => {
  if (!days) return ''
  if (days <= 3) return 'critical'
  if (days <= 7) return 'warning'
  return 'normal'
}

// 分页处理函数
const handleSizeChange = async (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
  await vipStore.fetchPaymentOrders(0, newSize)
}

const handleCurrentChange = async (newPage: number) => {
  currentPage.value = newPage
  await vipStore.fetchPaymentOrders(newPage - 1, pageSize.value)
}
</script>

<style scoped>
.subscription-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.subscription-card,
.orders-card {
  margin-bottom: 20px;
  transition: all 0.2s ease;
}

.subscription-management.dark .subscription-card,
.subscription-management.dark .orders-card {
  background: #1e293b;
  border-color: #334155;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #111827;
  transition: color 0.2s ease;
}

.subscription-management.dark .card-header h3 {
  color: #f1f5f9;
}

.upgrade-btn {
  background: #f59e0b;
  border: none;
  transition: background-color 0.2s ease;
}

.upgrade-btn:hover {
  background: #d97706;
}

.subscription-info {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  transition: all 0.2s ease;
}

.subscription-management.dark .subscription-info {
  border: 1px solid #334155;
  background: #0f172a;
}

.subscription-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.plan-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.plan-name {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #111827;
  transition: color 0.2s ease;
}

.subscription-management.dark .plan-name {
  color: #f1f5f9;
}

.subscription-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
  transition: border-color 0.2s ease;
}

.subscription-management.dark .detail-row {
  border-bottom: 1px solid #334155;
}

.label {
  color: #6b7280;
  font-size: 14px;
  transition: color 0.2s ease;
}

.subscription-management.dark .label {
  color: #94a3b8;
}

.value {
  color: #111827;
  font-weight: 500;
  transition: color 0.2s ease;
}

.subscription-management.dark .value {
  color: #f1f5f9;
}

.value.amount {
  color: #f59e0b;
  font-weight: 600;
}

.value.critical {
  color: #f56c6c;
}

.value.warning {
  color: #e6a23c;
}

.value.normal {
  color: #67c23a;
}

.no-subscription {
  text-align: center;
  padding: 40px 20px;
}

.subscription-history {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
  transition: border-color 0.2s ease;
}

.subscription-management.dark .subscription-history {
  border-top: 1px solid #334155;
}

.history-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  transition: color 0.2s ease;
}

.subscription-management.dark .history-title {
  color: #f1f5f9;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  padding: 15px;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  transition: all 0.2s ease;
}

.subscription-management.dark .history-item {
  background: #0f172a;
  border: 1px solid #334155;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #6b7280;
  transition: color 0.2s ease;
}

.subscription-management.dark .item-details {
  color: #94a3b8;
}

.cancel-content {
  margin: 20px 0;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Element Plus 夜间模式适配 */
.subscription-management.dark :deep(.el-card) {
  background: #1e293b;
  border-color: #334155;
}

.subscription-management.dark :deep(.el-card__header) {
  background: #0f172a;
  border-bottom: 1px solid #334155;
  color: #f1f5f9;
}

.subscription-management.dark :deep(.el-table) {
  background: #1e293b;
  color: #f1f5f9;
}

.subscription-management.dark :deep(.el-table th.el-table__cell) {
  background: #0f172a;
  color: #f1f5f9;
  border-bottom: 1px solid #334155;
}

.subscription-management.dark :deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #334155;
  color: #e2e8f0;
}

.subscription-management.dark :deep(.el-table tr) {
  background: #1e293b;
}

.subscription-management.dark :deep(.el-table tr:hover > td) {
  background: #334155;
}

.subscription-management.dark :deep(.el-empty) {
  color: #94a3b8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .subscription-management {
    padding: 10px;
  }
  
  .subscription-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .subscription-details {
    grid-template-columns: 1fr;
  }
  
  .detail-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .item-header,
  .item-details {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>